<?php
	header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
	header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

	// Includes
	require_once $_SERVER['DOCUMENT_ROOT'] . '/../include/apps/janus/includes.php';
	
	// Create our Application instance
	$facebook = new Facebook(array(
		'appId'  => $GLOBALS['FACEBOOK']['ID'],
		'secret' => $GLOBALS['FACEBOOK']['SECRET'],
		'cookie' => true,
		'domain' => 'leedsmet.ac.uk'
	));
	
	// Ensure there is a session for this user and the app has been granted basic permissions
	$session = JanusFacebook::checkSessionAuth($facebook);
	$facebook_id = $facebook->getUser();
	
	if ($session)
	{
		try
		{
			$application = $facebook->api($GLOBALS['FACEBOOK']['ID']);
			$appName     = htmlspecialchars($application['name']);
		}
		catch (FacebookApiException $e)
		{
			error_log($e);
			$appName = '#unknown#';
		}
	}
	
	JanusFacebook::checkApiAccess($facebook);
	
	// Load tabs template. By default, detected replacement codes are replaced with an empty 
	// string so only those that are specified will be replaced with something useful. 
	$template = new MarkupTemplate();
	$template->loadTemplateFile($GLOBALS['TEMPLATES']['BASE_PATH'] . 'fb_tabs.tpl', true);
	$template->updateReplacement('ACCOUNT_TAB_SELECTED', 'selected', false);
	$tabContent = $template->getOutputMarkup();
	
	if ($_POST['submit'])
	{
		// Convert all the posts to variables and strip any dodgy bits from them that might result in SQL injection attacks.
	  	$library_id = ereg_replace("[^A-Za-z0-9]", "", strtoupper($_POST['library_id']));
	   	$pin = ereg_replace("[^0-9]", "", $_POST['pin']); 
	   	$facebook_id = ereg_replace("[^0-9]", "", $_POST['facebook_id']);

	   	$errors = array();
		$err_messages = array();
	   	
		// Database connection
		$conn = JanusDb::getDbConnection();

		// check valid connection and manage errors 
		if (!$conn)
		{
			$errors[] = oci_error();
			$err_messages[] = "The database connection failed. Please try later.";
		}
		else if ($conn == true)
		{
			// Create query to check if the account is already registered
			$stid = @oci_parse($conn, "select count(*) from JANUS where LIBRARY_ID = :library_id and PIN = :pin");

			if (!$stid)
			{
				$errors[] = oci_error();
			}
	
			$bind_lib_id = @oci_bind_by_name($stid, ":library_id", $library_id);
			$bind_lib_pn = @oci_bind_by_name($stid, ":pin", $pin);
		
			if (!$bind_lib_id || !$bind_lib_pn)
			{
				$errors[] = oci_error();
			}

			$exec = @oci_execute($stid , OCI_DEFAULT); 
		
			if (!$exec)
			{
				$errors[] = oci_error();
				$err_messages[] = "This service is currently unavailable, please try later";
			}

			if ($exec == true)
			{
				// Result
				$result = @oci_fetch_array($stid, OCI_RETURN_NULLS);

				if($result == true)
				{
					if($result[0] == 0)
					{
						// This account is not registered and so can be
						$go_register = true;
					}
					elseif($result[0] == 1)
					{
						// This account is already registered and so can't be re-registered
						$go_register = false;
					}
					else
					{
						// Either no result or there is currently more than one registered account. Bad news.
						$go_register = false;			
					}
				} // End error handling for result 
			} // End EXEC error handling
			
			if ($go_register == true)
			{
				// Clear variables for reuse
				$free_statement = @oci_free_statement($stid);
			
				if (!$free_statement)
				{
					$errors[] = oci_error();
				}

				$stid = @oci_parse($conn, "insert into JANUS values (:facebook_id,:library_id,:pin)");
			
				if (!$stid)
				{
					$errors[] = oci_error();
				}
			
				$bind_lib_id = @oci_bind_by_name($stid, ":library_id", $library_id);
				$bind_lib_pn = @oci_bind_by_name($stid, ":pin", $pin);
				$bind_fc_id = @oci_bind_by_name($stid, ":facebook_id", $facebook_id);
			
				if (!$bind_lib_id || !$bind_lib_pn || !$bind_fc_id)
				{
					$errors[] = oci_error();
				}
		
				$exec = @oci_execute($stid , OCI_DEFAULT);
			
				// Commits all outstanding statements for the active transaction on the Oracle connection.
				$commit =  @oci_commit($conn);

				if (!$commit)
				{
					$errors[] = oci_error();
					@oci_rollback($conn);
				}
				else
				{
					$registration_result = "<p>Your account has been registered. <a href=\"index.php\">Return to account summary</a>.</p>";
				} // END of commit error handling
			} // END user is unique code

			// Logoff from Oracle
			@oci_free_statement($stid);
			@oci_close($conn); 
		} // End CONN error handling
	
		if (count($err_messages) > 0)
		{
			$registration_result = "<p>" . $err_messages[0] . "</p>";
		}

		$pageContent = $registration_result;
	}
	else
	{
		$pageContent = "<p><a href=\"index.php\">Return to Leeds Met Library App</a></p>";
	} // END POST IF
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" href="/main/apps/janus/css/janus.css" type="text/css" />
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
/* <![CDATA */
	window.fbAsyncInit = function() {
		FB.init({
			appId   : '<?php echo $facebook->getAppId(); ?>',
			session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
			status  : true, // check login status
			cookie  : true, // enable cookies to allow the server to access the session
			xfbml   : true // parse XFBML
		});

		// whenever the user logs in, we refresh the page
		FB.Event.subscribe('auth.login', function() {
			window.location.reload();
		});

		// Parse any FBML
		//FB.XFBML.parse();
	};
	
	(function() {
		var e = document.createElement('script');
		e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
		e.async = true;
		document.getElementById('fb-root').appendChild(e);
	}());
/* ]]> */
</script>
<h1><?php echo $appName; ?></h1>
<?php echo $tabContent; ?>
<?php echo $pageContent; ?>
</body>
</html>